package vip.xiaonuo.gateway.core.filter;

import cn.dev33.satoken.stp.StpUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.gateway.core.consts.GatewayAllowedIpProperties;

/**
 * @author zjt
 * @description
 * @date 2025/3/5 13:34
 */
@Slf4j
@Component
public class IpFilter implements GlobalFilter {

    @Resource
    private GatewayAllowedIpProperties allowedIpProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        if (allowedIpProperties.isEnabled()) {
            boolean isLogin = false;
            try {
                isLogin = StpUtil.isLogin();
            } catch (Exception ignored) {
            }
            if (isLogin) {
                SaBaseLoginUser loginUser = null;
                try {
                    loginUser = StpLoginUserUtil.getLoginUser();
                } catch (Exception e) {
                    log.error("请求拦截，获取当前用户失败", e);
                }
                if (loginUser != null) {
                    String clientIp = getClientIp(exchange);
                    if (!allowedIpProperties.getUser().contains(loginUser.getAccount()) && !allowedIpProperties.getIp().contains(clientIp)) {
                        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
                        log.error("请求拒绝：当前登录用户：{}，nacos用户：{}", loginUser.getAccount(), allowedIpProperties.getUser());
                        log.error("请求拒绝：当前登录IP：{}，nacos-IP：{}", clientIp, allowedIpProperties.getIp());
                        return exchange.getResponse().setComplete();
                    }
                }
            }
        }
        return chain.filter(exchange);
    }

    /**
     * 获取客户端 IP 地址
     */
    private String getClientIp(ServerWebExchange exchange) {
        String ip = exchange.getRequest().getHeaders().getFirst("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = exchange.getRequest().getHeaders().getFirst("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = exchange.getRequest().getHeaders().getFirst("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = exchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
        }
        return ip;
    }
}
